<?php

class Controller_Mail extends Controller_Base
{
	private $show_in_page = 1;
	private $pause        = 5;
	public $email_add_other = false;
	public $email = false;
	public $arrayMessage  = array(
		'TIMEOUT'  => 'Ошибка! Следующее сообщение можно отправить только через %i мин. %s сек.!',
		'SUCCESS'  => 'Спасибо! Сообщение успешно отправлено!',
		'F_EMPTY'  => 'Не заполнены обязательные поля!'
	);
		
	public function __construct($parts) {		
		$this->parts        = $parts;
		$this->common_vars  = Registry::get("common_vars");
		$this->table_module = PRFX."mail";
		$this->table_log    = PRFX."mail_log";
		$this->tree_site    = Registry::get("tree_site");
	}
	
	/*
	 * Антиспам (проверка на наличие спама, ограничение количества сообщений 
	 * в $this->pause минут, проверка на заполненность обязательного поля)
	 * $form_array (array) = Массив отправленный с формы
	 * $items_fields (array) = Массив с полями формы
	 */
	public function antispam($form_array = array(), $items_fields = array(), $this_id = false) 
	{	
		foreach($items_fields as $Key => $Array) {				
			if($Array['mandatory'] && (empty($_POST['form'.$this_id][$Key]))) {
				self::error("F_EMPTY");
				break;
			}
		}
		if(empty($this->error))	{	
			$r =& Registry::get("MDB")->query("SELECT `Date` FROM `".$this->table_log."` WHERE `Ip` = '".getenv("REMOTE_ADDR")."' AND `Date` > '".(time()-($this->pause*60))."' AND `Parent` = '".$this_id."' ORDER BY `Date` DESC LIMIT 1;");
			if (PEAR::isError($r)) {
				die($r->getMessage().' ::: '.$r->getUserInfo());
			}
			if($r->numRows()) {
				$item = $r->fetchRow(MDB2_FETCHMODE_ASSOC);	
				$this->last_message_time = $item["date"];
				self::error("TIMEOUT");
			}
			else {
				self::send($items_fields, $this_id);					
			}
		}		
	}
	
	public function send($items = false, $this_id = false)
	{		
		$ip = getenv("REMOTE_ADDR");
		foreach($items as $Key => $Array) {		
			if(!empty($Array['name'])) {
				$body.= $Array['name'].': '.$_POST['form'.$this_id][$Key].'<br>';
			}
		}
		$body.= '<br>IP адрес отправителя: '.$ip.'<br>сообщение было отправлено '.date("d.m.Y").' в '.date("H:i").'<br>
				 Сайт: www.'.str_replace(array(
				 	"www.",
					"http://",
					"https://"
				), "", $_SERVER['HTTP_HOST']);		

		$mail = new PHPMailer(true);
		try
		{
			$mail->Subject = $this->subject;
			$mail->SetFrom($this->from, $this->fromname);
			$mail->CharSet = 'utf-8';
			$mail->Encoding = 'base64';			
			foreach($this->email as $email) {			
				$mail->AddAddress($email);
				$mail->MsgHTML('<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body>'.$body.'</body></html>');
				$mail->Send();
				$mail->ClearAddresses();
			}			
		}
		catch(phpmailerException $e) {
			echo $e->errorMessage();			
		}
		catch(Exception $e) {
			echo $e->getMessage();
		}

		$date = time();
		$parent = $this_id;	
		eval(functions::insert_sql($this->table_log, 'sql'));
		$r =& Registry::get("MDB")->query($sql);
		if (PEAR::isError($r)) {
			die($r->getMessage().' ::: '.$r->getUserInfo());
		}	
		self::error("SUCCESS");
		$_SESSION["form_message"] = $this->error;
		header("Location: ".$_SERVER['REQUEST_URI']);
		exit();
	}	
	
	public function error($code) {
		if($code == "TIMEOUT") {
			$time_difference = ($this->last_message_time - (time()-($this->pause*60)));
			$this->arrayMessage[$code] = str_replace(array("%i","%s"), array(date("i", $time_difference), date("s", $time_difference)), $this->arrayMessage[$code]);			
		}
		$this->error = $this->arrayMessage[$code];		
	}
	
	/* Запись */
	public function once_items($sql = false)
	{
		$r = & Registry::get("MDB")->query("SELECT * FROM `".$this->table_module."` WHERE ".$sql." `Show` = '1' AND `Parent`='".$this->common_vars["structure_id"]."' LIMIT 1;");
		if(PEAR::isError($r)) {
			die($r->getMessage().' ::: '.$r->getUserInfo());
		}
		if($r->numRows())
		{
			$item = $r->fetchRow(MDB2_FETCHMODE_ASSOC);			
			
			Registry::set("title", functions::createTitle(array($this->common_vars["structure_name"], $item["name"]), $item["title"]));			
			Registry::set("description", $item["description"]);
			Registry::set("keywords", $item["keywords"]);			
						
			$item["field"] = __unserialize($item["field"]);
			$item["email"] = __unserialize($item["email"]);
			
			if(!empty($this->email_add_other)) {
				if(is_array($this->email_add_other)) {
					$item["email"] = array_merge($item["email"], $this->email_add_other);						
				} elseif(is_array($this->email_add_other)) {
					$item["email"][] = $this->email_add_other;
				}
			}			
			/* Создаем конфиг-массив с полями формы */
			foreach($item["field"] as $Key => $Array) {
				$form_fields[$Key]['name'] = $Array['namefield'];
				$form_fields[$Key]['type'] = $Array['typefield'];
				$form_fields[$Key]['mandatory'] = $Array['obfield'] ? 1 : 0;
				if(!empty($Array['fieldarray'])) {
					$form_fields[$Key]['val'] = $Array['fieldarray'];
				}
			}			
			/* Изображения */
			for($j=1;$j<=40;$j++) {
				unset($tmp_image, $width, $height);						
				$tmp_image = functions::getImage("mail", $item["id"], $item["name"], $j, "450x213_mail_gallery_trumbnail.jpg", "background", "md5", &$width, &$height);						
				if($tmp_image) {
					$image_gallery[$j]["pic"] = $tmp_image;
					$image_gallery[$j]["w"] = $width;
					$image_gallery[$j]["h"] = $height;
				}
			}			
			/* Форма */
			if(!empty($_POST["form".$item["id"]])) {
				$this->subject = $item["subject"];
				$this->from = $item["from"];
				$this->fromname = $item["fromname"];
				$this->email = $item["email"];			
				self::antispam($_POST, $form_fields, $item["id"]);
			}
			
			/* Если есть сообщение, то выводим и удаляем сессию */
			if(!empty($_SESSION["form_message"])) {
				$this->error = $_SESSION["form_message"];
				unset($_SESSION["form_message"]);	
			}	
				
			return array(
				"name"       => $item["name"],
				"text"       => $item["text"],
				"text_after" => $item["text_after"],
				"is_header"  => $item["is_header"],
				"image_gallery" => $image_gallery,
				
				"ERROR"       => $this->error,
				"FIELD_ARRAY" => $form_fields,
				"UID"         => "form".$item["id"],
				"POST_UID"    => $_POST["form".$item["id"]],
				
				/* Меню новостей справа */
				//"menu_news"   => menu::getSubMenuNews(56),
				/* Меню акций справа */
				///"menu_action"   => menu::getSubMenuNews(57)
			);			
		}		
	}

    public function out()
	{     
		$this->all_count = functions::count_position($this->table_module, $this->common_vars["structure_id"]);	
        if (empty($this->parts[2]) && ($this->all_count > $this->show_in_page)) {
            $nav_limit = functions::page_num($this->parts[1], $_GET['page'], $this->all_count, $this->show_in_page);
			$this->limit = $nav_limit["limit"];
			$this->navyg = $nav_limit["navyPages"];
        }
		/* Если одна запись */
        if ($this->all_count == 1 && empty($this->parts[2])) {		
			$out = self::once_items();
        }
		/* Если больше одной записи */
		elseif($this->all_count > 1)
		{
		    if(empty($this->parts[2]))
			{ 
				$r = & Registry::get("MDB")->query("SELECT * FROM `".$this->table_module."` WHERE `Show`='1' AND `Parent`='".$this->common_vars["structure_id"]."' ORDER BY `Por` ".$this->limit.";");
                if (PEAR::isError($r)) {
                    die($r->getMessage().' ::: '.$r->getUserInfo());
                }				
				if($r->numRows())
				{					
					$C_ARRAY = array();				
					while($item = $r->fetchRow(MDB2_FETCHMODE_ASSOC)) {
						$C_ARRAY[] = array(							
							"item_vars" => $item
						);				
					}
					$out['navygation'] = $this->navyg;
					$out['c_array']    = $C_ARRAY;											
				}
				
            }
			else {
                $out = self::once_items("`Sys_name` = '".$this->parts[2]."' AND '");
            }			
        }	
		
		$out['header']      = $this->tree_site[0]["name"];
		$out['header_link'] = $this->tree_site[0]["redirect"] ? $this->tree_site[0]["redirect"] : "/".$this->tree_site[0]["sys_name"].ENDURL;
		//$out['LEFT_MENU']   = (!in_array($this->parts[1], Registry::get("NoneLeftMenuSection")) ? menu::getSubMenu($this->tree_site[0]["id"], $this->parts[1]) : '');
		$out['menu'] = (!in_array($this->parts[1], Registry::get("NoneLeftMenuSection")) ? menu::getMainMenu(true, $this->tree_site[0]["id"]) : '');

		Registry::set("title", functions::createTitle(array($this->common_vars["structure_name"]), ''));		
		
		Registry::get("smarty")->assign($out);
		return Registry::get("smarty")->fetch(TEMPLATE_SITE.$this->common_vars["controller_template"], Registry::get("cache_id"));	
    }
}

$controller = new Controller_Mail($parts);
$site_module_out = $controller->out();

?>